package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// https://medium.com/learning-the-go-programming-language/streaming-io-in-go-d93507931185
func t_io_reader() {
	reader := strings.NewReader("clear is better than clever")

	p := make([]byte, 4) // 故意选择一个比string source要小得多的buffer length

	for {
		n, err := reader.Read(p)
		if err != nil {
			// 不等于nil时考虑EOF和非EOF
			if err == io.EOF {
				fmt.Println(string(p[:n]))
				break
			}
			fmt.Println(err)
			os.Exit(-1)
		}
		fmt.Println(string(p[:n]))
	}
}


// customize a reader
type AlphaReader struct {
	src string
	cur int
}

func newAlphaReader(src string) *AlphaReader {
	return &AlphaReader{src:src}
}

func alpha() {

}

func (a *AlphaReader) Read(p []byte) (int, error)  {
	// to do
	return 0, io.EOF
}

func t_cutomized_reader()  {
	reader := newAlphaReader("hello, world. today it's 7 pm.")
	p := make([]byte ,4)
	for {
		n, err := reader.Read(p)
		if err == io.EOF {
			break
		}
		fmt.Println(string(p[:n]))
	}
}

func main() {
	t_io_reader()
	t_cutomized_reader()
}
